import { getProfileAPI } from './apis/user';
/*
 * @Author: LBH 1336709799@qq.com
 * @Date: 2024-12-09 21:18:55
 * @LastEditors: LBH 1336709799@qq.com
 * @LastEditTime: 2024-12-13 22:34:44
 * @FilePath: \hm-admin\src\permission.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 权限控制
import type { RouteRecordRaw } from 'vue-router'
import router from './router'
import { useMenuStore, useUserStore } from './stores/user'
import { getLocalToken } from './utils/auth'
import { asyncRoutes } from './router/asyncRoutes'

const WHITE_LIST = ['/login', '/404']
/**
 * 处理一级路由数据
 */
const getFirstRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    // 过滤掉没有一级路由的权限
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}
// 处理二级路由权限数据
const getSecondRoutePerms = (permsArr: string[]) => {
  const newArr = permsArr.map(item => {
    // 过滤掉没有二级路由的权限
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(newArr)]
}
// 根据权限标识过滤路由表
const getRoutes = (firstRoutePerms: string[], secondRoutePerms: string[], asyncRoutes: RouteRecordRaw[]) => {
  if (firstRoutePerms.includes("*")) {
    // 管理员（拷贝 - 防止重复登录同一个用户时，此变量值返回给外面后不断 push * 地址，导致左侧菜单 key 重复报错问题）
    return [...asyncRoutes];
  }
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  const firstRoutes = asyncRoutes.filter((route: RouteRecordRaw) => {
    return firstRoutePerms.includes(route.meta!.permission!)
  })
  console.log(firstRoutes)

  // 2. 对二级路由做过滤
const lastRoutes = firstRoutes.map((item: RouteRecordRaw) => {
    return {
      ...item,
      children: item!.children!.filter(obj => secondRoutePerms.includes(obj.meta!.permission!))
    }
  })
  return lastRoutes
}
// 2. 路由全局前置守卫
router.beforeEach(async (to, from, next)=>{
  // 2.1 获取token
  const token = getLocalToken()
  // 2.2 判断是否有token
  if(token){
    // 2.2.1 判断去的页面是否是登录页, 如果是则拦截到首页
    if(to.path === '/login'){
      next('/')
    } else {
      // 2.2.2 获取用户权限数据
      const store = useUserStore()
      if(!store.profile.id){
        const res =  await getProfileAPI()
        store.setProfile(res.data)
        console.log(res, '2222')
        // 获取一级路由标识
        const menu = getFirstRoutePerms(res.data.permissions)
        console.log(menu)
        // 获取二级路由标识
        const sMenu = getSecondRoutePerms(res.data.permissions)
        console.log(sMenu)
        // 根据权限标识过滤路由表
        const perRoutes = getRoutes(menu, sMenu, asyncRoutes)
  
        // 把动态路由表加入到路由系统中（当浏览器中访问路由的路径 显示渲染出来对应的组件）
        perRoutes.push(
          // 404 地址配置为*=》匹配不存在的地址，放到过滤动态路由规则后边
          {
            path: "/:pathMatch(.*)*",
            component: () => import("@/views/NotFound.vue"),
            meta: { hidden: true },
            children: [],
          }
        );
        perRoutes.forEach(route => {
        	router.addRoute(route)
        })

        //存入Pinia渲染左侧菜单
        const menuStore = useMenuStore()
        // 设置菜单
        menuStore.setMenuList(perRoutes)

        next({...to});
      }  

      next()
    }
  }else{
    // 2.2.2 判断是否在白名单
    if(!WHITE_LIST.includes(to.path)){
      next('/login')
    }else{
      next()
    }
  }
})